<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="单据编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="单据编号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="供应商" prop="supplierName" width="120"/>
      <el-table-column label="单据编号" prop="receiptNumber" :show-overflow-tooltip="true" width="180"/>
      <el-table-column label="商品信息" prop="goodsInfo" :show-overflow-tooltip="true" width="150"/>
      <el-table-column label="单据日期" prop="billDate" width="100"/>
      <el-table-column label="操作员" prop="adminName" width="100"/>
      <el-table-column label="退还金额" prop="returnAmount"/>
      <el-table-column label="实退金额" prop="payAmount"/>
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.returnAmount === scope.row.payAmount" style="color: #13ce66">已退款</span>
          <span v-else style="color: #ee83f4">未退款</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改配置对话框 -->
    <el-dialog title="添加采购退货单" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px" :inline="true" style="width: 100%;padding: 20px">
        <el-form-item>
          <el-button icon="el-icon-search" @click="showCgorderDialog" size="mini">关联采购订单</el-button>
        </el-form-item>
        <el-table :data="selectCgorderList">
          <el-table-column label="供应商" prop="supplierName"/>
          <el-table-column label="单号" prop="receiptNumber" width="180"/>
          <el-table-column label="单据日期" prop="billDate"/>
          <el-table-column label="操作员" prop="adminName"/>
          <el-table-column label="总价" prop="totalAmount">
          </el-table-column>
          <el-table-column label="优惠" prop="discountAmount"/>
          <el-table-column label="实付金额" prop="realAmount"/>
          <el-table-column label="状态" align="center" width="100">
            <template slot-scope="scope">
              <span style="color: #13ce66" v-if="scope.row.state === 0">已审核</span>
              <span style="color: #e05858" v-else-if="scope.row.state === 1">待审核</span>
              <span style="color: #15e3f6" v-else-if="scope.row.state === 2">已入库</span>
            </template>
          </el-table-column>
        </el-table>
        <br/>
        <div style="width: 100%">
          <el-input type="textarea" v-model="form.note" placeholder="订单备注"/>
        </div>
        <br/>
        <el-form-item label="结算账户" prop="accountId">
          <el-select v-model="form.accountId" placeholder="请选择结算账户" size="mini">
            <el-option v-for="account in accounts"
                       :key="account.id"
                       :value="account.id"
                       :label="accountLabel(account)">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单总额" prop="totalAmount">
          <el-input v-model="calculatedTotalAmount" disabled placeholder="" size="mini"/>
        </el-form-item>
        <el-form-item label="优惠金额" prop="discountAmount">
          <el-input v-model="calculatedDiscountAmount"  disabled placeholder="" size="mini"/>
        </el-form-item>
        <el-form-item label="选择仓库" prop="storeId">
          <el-select v-model="form.storegeId" placeholder="请选择仓库" size="mini">
            <el-option v-for="store in stores"
                       :key="store.id"
                       :value="store.id"
                       :label="store.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="退货收款" prop="payAmount">
          <el-input v-model="form.payAmount" placeholder="" size="mini"/>
        </el-form-item>
        <el-form-item label="本次欠款" prop="debtAmount">
          <el-input v-model="calculatedDebtAmount" readonly placeholder="" size="mini"/>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button type="primary" @click="submitForm">添加并审核</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 选择采购单的弹窗 -->
    <el-dialog title="选择采购订单" :visible.sync="goodsListOpen" width="1000px" append-to-body>

      <el-table ref="cgorderTable" :data="goodsList" @selection-change="handleCgorderSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="供应商" prop="supplierName" width="120"/>
        <el-table-column label="单据编号" prop="receiptNumber" :show-overflow-tooltip="true" width="180"/>
        <el-table-column label="商品信息" prop="goodsInfo" :show-overflow-tooltip="true" width="150"/>
        <el-table-column label="单据日期" prop="billDate" width="100"/>
        <el-table-column label="操作员" prop="adminName" width="100"/>
        <el-table-column label="总价" prop="totalAmount"/>
        <!--        <el-table-column label="优惠" prop="discountAmount"  />-->
        <!--        <el-table-column label="定金" prop="depositAmount"  />-->
        <el-table-column label="状态" align="center" width="100">
          <template slot-scope="scope">
            <span style="color: #13ce66" v-if="scope.row.state === 0">已审核</span>
            <span style="color: #e05858" v-else-if="scope.row.state === 1">待审核</span>
            <span style="color: #15e3f6" v-else-if="scope.row.state === 2">已入库</span>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="goodsListOpen = false">确 定</el-button>
        <el-button @click="cgorderListDialogCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import {addOrder, listOrder} from "@/api/purchase/order";
import {listSupplier} from "@/api/base/supplier";
import {listAccount} from "@/api/base/account";
import {listStorage} from "@/api/base/storage";
import {addStore, listStore, delStore} from "@/api/purchase/store";
import {addReturn, delReturn, listReturn} from "@/api/purchase/return";

export default {
  name: "cgstore",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      showSearch: true,
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 表格数据
      dataList: [],
      stores: [],
      //商品列表
      goodsList: [],
      accounts: [],
      //选中的商品
      selectCgorderList: [],
      //第一个弹窗
      open: false,
      //第二个弹窗
      goodsListOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: ""
      },
      // 表单参数
      form: {
        storegeId:"",// 仓库id
        orderNo: "", //订单号
        accountId: "", //结算账户ID
        depositAmount: "", //定金
        payAmount: "",//付款金额
        totalAmount: "",//总额
        debtAmount: "0",//欠款
        orderList: "", //采购单集合
      },
      defaultProps: {
        children: "children",
        label: "label"
      }
    };
  },
  created() {
    this.getList();
    this.getOrderList();
  },
  computed: {
    calculatedTotalAmount() {
      return this.selectCgorderList.reduce((total, order) => total + order.totalAmount, 0);
    },
    calculatedDiscountAmount() {
      return this.selectCgorderList.reduce((total, order) => total + order.discountAmount, 0);
    },
    calculatedDepositAmount() {
      return this.selectCgorderList.reduce((total, order) => total + order.depositAmount, 0);
    },
    calculatedDebtAmount() {
      return (this.calculatedTotalAmount - this.calculatedDiscountAmount) - this.form.payAmount;
    },
  },
  methods: {
    accountLabel(account) {
      return `${account.name} - ${account.sn}`;
    },
    updateOrderAmounts() {
      this.form.totalAmount = this.selectCgorderList.reduce((total, order) => total + order.totalAmount, 0);
      this.form.discountAmount = this.selectCgorderList.reduce((total, order) => total + order.discountAmount, 0);
      this.form.depositAmount = this.selectCgorderList.reduce((total, order) => total + order.depositAmount, 0);
      this.form.debtAmount = this.form.totalAmount - this.form.payamount;
    },
    cancel() {
      this.open = false;
    },
    cgorderListDialogCancel() {
      this.goodsListOpen = false;
      this.selectCgorderList = [];
      this.$refs.cgorderTable.clearSelection();
    },
    showCgorderDialog() {
      this.goodsListOpen = true;
    },
    /** 查询采购订单列表 */
    getList() {
      this.loading = true;
      listReturn(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询采购订单列表 */
    getOrderList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.goodsList = response.rows.filter(item => item.state === 2);
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询结算账户列表 */
    getAccounts() {
      this.loading = true;
      listAccount(this.queryParams).then(response => {
        this.accounts = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询入库单列表 */
    getStores() {
      this.loading = true;
      listStorage(this.queryParams).then(response => {
        this.stores = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleCgorderSelectionChange(selection) {
      this.selectCgorderList = selection;
      this.form.orderList = selection;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.getOrderList();
      this.getAccounts();
      this.getStores();
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const order = {
            note: this.form.note,
            accountId: this.form.accountId, // 结算账户id
            orderList: this.form.orderList, // 采购单信息
            adminName: this.$store.state.user.name,
            totalAmount: this.calculatedTotalAmount, // 传递订单总额
            discountAmount: this.calculatedDiscountAmount, // 传递优惠金额
            depositAmount: this.calculatedDepositAmount, // 传递扣除定金
            payAmount: this.form.payAmount, // 传递本次付款
            debtAmount: this.calculatedDebtAmount, // 传递本次待付金额
            storeId: this.form.storegeId, //
            state:1
          };
          addReturn(order).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除入库编号为"' + ids + '"的数据项？').then(function() {
        return delReturn(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/role/export', {
        ...this.queryParams
      }, `role_${new Date().getTime()}.xlsx`)
    }
  },

  mounted() {

  }
};
</script>
